package xxx;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

public class MainApp {

    static Properties properties;
    static SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS" );

    public static void main(String... args) throws Exception {
        String input_dir = prop("xml.input.dir");
        String merge_dir = prop("xml.merge.dir");
        String begin = format.format(new Date());

        new File(input_dir).mkdirs();
        new File(merge_dir).mkdirs();

        File merge_file = new File(merge_dir + File.separator + UUID.randomUUID().toString() + ".xml");

        BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(merge_file), 1073741824);
        byte[] buffer = new byte[1048576];

        Files.walk(Paths.get(input_dir))
                .filter(path -> {
                    if(!Files.isRegularFile(path))
                        return false;
                    if(!path.getFileName().toString().endsWith(".xml"))
                        return false;
                    return true;
                })
                .forEach(path -> {
                    System.out.println(path.getFileName());
                    BufferedInputStream in = null;
                    try {
                        in = new BufferedInputStream( new FileInputStream(path.toFile()));
                        int size;
                        while ((size = in.read(buffer)) != -1)
                        {
                            out.write(buffer, 0, size);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if(in!=null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }


                });
        out.flush();
        out.close();

        String end = format.format(new Date());
        System.out.println("begin: " + begin);
        System.out.println("end: " + end);
    }

    static String prop(String key) throws IOException {
        if(properties !=null){
            return properties.getProperty(key);
        }
        properties= new Properties();
        FileInputStream f = new FileInputStream("application.properties");
        properties.load(f);
        f.close();

        return properties.getProperty(key);
    }
}

